package org.example.utils;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.base.RocketMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author huangy
 * @description rocketMq工具类
 * @since 2022/11/9 20:20
 **/
@Component
public class RocketMqUtils {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /*
     * @description 发送消息
     * @author huangy
     * @since 2022/11/10 15:42
     * @param topic 主题
     * @param tag 标签
     * @param body 消息体
     * @return org.apache.rocketmq.client.producer.SendResult
     **/
    public SendResult syncSendMessage(String topic, String tag, Object body) {
        return syncSendMessage(RocketMessage.valueOf(topic, tag, body));
    }

    /*
     * @description 发送消息
     * @author huangy
     * @since 2022/11/10 15:43
     * @param rocketMessage
     * @return org.apache.rocketmq.client.producer.SendResult
     **/
    public SendResult syncSendMessage(RocketMessage<?> rocketMessage) {
        String bodyJson = JSON.toJSONString(rocketMessage.getBody());
        return rocketMQTemplate.syncSend(rocketMessage.getTopic() + ":" + rocketMessage.getTag(), bodyJson);
    }

}
